
import { View, Text, Image, Button } from '@tarojs/components'
import styles from "./index.module.scss";
import "./index.scss";
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { AtButton, AtList, AtListItem, AtProgress, AtCountdown } from 'taro-ui'
import React, { Fragment } from 'react';
import { BaseComponents, Layout, GetRiceDialog } from "@/components";
import { isLogin } from '@/utils/common'

import banner from "@/images/home/banner.png"
import headerDefault from "@/images/home/header_photo_default.png"
import quote from "@/images/home/icon-quote.png"
import volume from "@/images/home/icon_volume.png"
import rice from "@/images/my/icon_rice.png"

import { lotteryListApi, treasureListApi, winListApi, getAdsApi, getCreditApi } from '@/api/home';
import { getUserinfoApi, getSoupInfoApi } from '@/api';





interface Props { }
interface State {
  userInfo: any;
  scene: string;
  lotteryList: any[];
  treasureList: any[];
  winList: any[];
  house: number;
  minute: number;
  second: number;
  isOpened: boolean;
  adsInfo: any;
  loadding: boolean;
  soupInfo: any[];
  height:number;
  animate:boolean;
  loaddingButton:boolean;
}

export default class Index extends BaseComponents<Props, State> {
  $instance = getCurrentInstance();
  constructor(props: Props) {
    super(props);

    this.state = {
      userInfo: {},
      scene: "",
      lotteryList: [],
      treasureList: [],
      winList: [],
      house: 0,
      minute: 0,
      second: 0,
      isOpened: false,
      adsInfo: [],
      loadding: false,
      soupInfo: [],
      height:0,
      animate:false,
      loaddingButton:false,
    };
  }

  componentWillMount() {
    let scene = this.$instance.router.params.scene;
    // let scene="9ad2e5dfbef612e6313e59e80d447801"
    if (scene) {
      this.setState({ scene });
    }
  }

  componentDidMount() {
    this.setState({ loadding: true });
    this.getWinList();
    this.getSoupInfo();
    this.getAds();
    setTimeout(() => {
      const query = Taro.createSelectorQuery()
      query.select('.main').boundingClientRect((rec: any) => {
        this.setState({height:rec.height});
      }).exec()
    }, 500)
  }

  componentWillUnmount() { }

  componentDidShow() {
    if (Taro.getStorageSync('userInfo')) {
      getUserinfoApi().then((res) => {
        Taro.setStorageSync('userInfo', res);
        this.setState({ loadding: false });
        this.setState({ userInfo: res });
      })
    } else {
      this.setState({ loadding: false, userInfo: {} });
    }
    lotteryListApi().then((res: any) => {
      if (res) {
        this.setState({ lotteryList: res });
        this.countDown(res[0].openTime);
      }
    });
    treasureListApi().then((res: any) => {
      if (res) {
        res.map((item) => {
          item.percent = Math.floor((item.currentCredits / item.totalCredits) * 100)
        })
        this.setState({ treasureList: res })
      }
    });

  }

  componentDidHide() { }

  //下拉时触发的函数
  onPullDownRefresh() {
    let pages = Taro.getCurrentPages();;
    let currPage: any = null;
    if (pages.length) {
      currPage = pages[pages.length - 1];
    };
    currPage.onShow();
    Taro.stopPullDownRefresh();
  }

  //获取心灵鸡汤
  getSoupInfo = () => {
    getSoupInfoApi().then((res: any) => {
      if (res) {
        this.setState({ soupInfo: res });
      }
    })
  }

  //获取广告
  getAds = () => {
    getAdsApi(this.state.scene).then((res: any) => {
      if (res) {
        res.map((item,index)=>{
          let url=item.ads[0].url;
          if(url){
            item.ads[0].url=url.split("?")[1].split("=")[1];
          }
        })
        this.setState({ adsInfo: res });
        Taro.setStorageSync('getAds', res);
        if (this.state.scene) {
          this.setState({ isOpened: true });
        }
      }
    })
  }
  //领取积分
  getCrite = () => {
    const { adsInfo, scene } = this.state;
    this.setState({loaddingButton:true});
    getCreditApi({ adCode: adsInfo[0].ads[0].code, credits: adsInfo[0].ads[0].credits, scene, userCode: Taro.getStorageSync("userInfo").code }).then((res) => {
      this.setState({loaddingButton:false,isOpened: false });
      if (res) {
        Taro.showToast({
          title: "积分领取成功!",
          icon: "none",
          duration: 1500
        })
        getUserinfoApi().then((res) => {
          Taro.setStorageSync('userInfo', res);
          this.setState({ loadding: false });
          this.setState({ userInfo: res });
        })
      }
    })
  }

  //倒计时
  countDown = (time) => {
    // let nightTime = new Date(new Date().toLocaleDateString()).getTime() + 18 * 60 * 60 * 1000;
    let nightTime = new Date(time).getTime();
    let newTime = new Date().getTime();
    let lefttime = Math.floor((nightTime - newTime) / 1000);
    let h = Math.floor(lefttime / (60 * 60) % 24);
    let m = Math.floor(lefttime / 60 % 60);
    let s = Math.floor(lefttime % 60);
    this.setState({
      house: h,
      minute: m,
      second: s,
    });
  }

  //参加夺宝
  treasureJoin = (code) => {
    if (isLogin()) {
      Taro.navigateTo({
        url: `/pages/treasureDetail/index?code=${code}`
      })
    }
  }
  //参加抽奖
  lotteryJoin = (code) => {
    if (isLogin()) {
      Taro.navigateTo({
        url: `/pages/lotteryDetail/index?code=${code}`
      })
    }
  }
  //获取中奖播报列表
  getWinList = () => {
    winListApi(1, 10).then((res: any) => {
      if (res) {
        this.setState({ winList: res.records });
        if(res.records.length>1)setInterval(this.Dt, 4000);
      }
    })
  }
  Dt= ()=> {
    this.setState({ animate: true });
    setTimeout(() => {
      this.state.winList.push(this.state.winList[0]);
      this.state.winList.shift();
      this.setState({ animate: false });
    }, 1000)
  }

  goAdsWebView = (webUrl) => {
    Taro.navigateTo({
      url: `/pages/webView/index?webUrl=${webUrl}`
    })
  }



  render() {
    const { lotteryList, treasureList, winList, house, minute, second, isOpened,  adsInfo, userInfo, loadding, soupInfo,height,animate,loaddingButton} = this.state;
    return (
      <Layout tabBar title="真香生活" loadding={loadding}>
        <View className={styles.index} style={{"height":`${height+380}px`}}>
          <View className={styles.banner} onClick={() => this.goAdsWebView(adsInfo[1].ads[0].url)}>
            <Image src={adsInfo.length > 0 && adsInfo[1].ads[0].adImg} mode="widthFix"></Image>
          </View>
          <View className={styles.titelCard}>
            <Image src={(userInfo && userInfo.avatar) ? userInfo.avatar : headerDefault} onClick={() => { isLogin(); Taro.switchTab({ url: "/pages/my/index" }); }} className={styles.headPhoto}></Image>
            {userInfo.credits ? <Fragment>
              <View className={styles.name}>{userInfo.alias}</View>
              <View className={styles.rice}>
                <Text className={styles.riceNumber}>{userInfo.credits ? userInfo.credits : 0}</Text>
                <Image src={rice}></Image>
              </View>
            </Fragment> :
              <Fragment>
                <Image src={quote} className={styles.quoteImg}></Image>
                <Text className={styles.textContent}>{soupInfo.length > 0 && soupInfo[0].content}</Text>
              </Fragment>
            }
          </View>

          <View className={"main"}>
            {winList.length > 0 && <View className={styles.notice}>
              <View className={styles.notice_left}>
                <Image src={volume}></Image>
                <Text>往期获奖</Text>
              </View>
              {/* <View className={styles.notice_right}>
                <View>恭喜{winList[index].alias}抽中{winList[index].name}</View>
              </View> */}
              <View className={`${styles.notice_right} ${animate&&styles.anim}`}>
              {winList.map((item,index)=>{
                return <View key={index}>恭喜{item.alias}抽中{item.name}</View>
              })}
              </View>
            </View>}

            {/* 夺宝 */}
            {treasureList.length > 0 &&
              <View className={styles.treasure} style={{ "marginTop": winList.length == 0 ? "0px" : "24px" }}>
                {treasureList.map((item, index) => {
                  return <View className={styles.treasure_item} onClick={() => this.treasureJoin(item.code)} key={index}>
                    <View className={styles.treasure_item_top}>
                      <Image src={item.bannerImg} mode="aspectFit"></Image>
                      {item.userJoinCnt > 0 && <Text>已参加{item.userJoinCnt}次</Text>}
                      <View className={styles.number}>数量 x {item.giftNum}</View>
                    </View>
                    <View className={styles.treasure_item_bottom}>
                      <View className={styles.name}>{item.content}</View>
                      <View className={styles.price}>
                        <Image src={rice}></Image>
                        <Text className={styles.price_new}>{item.credits}</Text>
                        <Text className={styles.price_old}>¥ {item.originalPrice}</Text>
                      </View>
                      <View className={styles.progress}>
                        <AtProgress percent={item.percent} strokeWidth={4} color='#7676FA' isHidePercent className={styles.atProgress} />
                        <Text >进度{item.percent}%</Text>
                      </View>
                      <View className={styles.join}>
                        <Button className={styles.batton}>{item.userJoinCnt ? "继续参加" : "立即参与"}</Button>
                      </View>
                    </View>
                  </View>
                })}

              </View>}

            {/* 抽奖 */}
            <View className={styles.lottery} style={{ "marginTop": treasureList.length == 0 ? "0px" : "24px" }}>
              <View className={styles.lottery_title}>
                <Text>今日抽奖</Text>
                {(house <= 0 && minute <= 0 && second <= 0) ? <Text className={styles.end}>已开奖</Text> : <Fragment>
                  <Text className={styles.end}>距结束</Text>
                  <AtCountdown
                    format={{ hours: ':', minutes: ':', seconds: '' }}
                    hours={house}
                    minutes={minute}
                    seconds={second}
                    className={styles.countDown}
                  />
                </Fragment>}
              </View>
              {lotteryList.length > 0 && lotteryList.map((item, index) => {
                return <View className={styles.lottery_item} onClick={() => this.lotteryJoin(item.code)} key={index}>
                  <Image src={item.bannerImg} mode="aspectFit"></Image>
                  <View className={styles.lottery_item_right}>
                    <View className="at-row at-row__justify--between">
                      <View className='at-col at-col-5'>
                        <View className={styles.name}>{item.content}</View>
                      </View>
                      <View className='at-col at-col-5' style={{ "textAlign": "right" }}>
                        <Text className={styles.number}>x {item.giftNum}</Text>
                      </View>
                    </View>
                    <View className="at-row at-row__justify--between">
                      <View className='at-col at-col-5'>
                        <Text className={styles.priceKey}>价值</Text>
                        <Text className={styles.priceValue}>¥ {item.originalPrice}</Text>
                      </View>
                      <View className='at-col at-col-5' style={{ "textAlign": "right" }}>
                        <Text className={styles.priceKey}>{item.joinCnt}人报名</Text>
                      </View>
                    </View>
                    <Button className={styles.batton} >{item.credits}米粒参加</Button>
                  </View>
                </View>
              })}

            </View>
          </View>
        </View>
        <GetRiceDialog isOpened={isOpened} adsInfo={adsInfo.length > 0 && adsInfo[0]} onCancel={() => { this.setState({ isOpened: false }) }} getCrite={() => this.getCrite()} loaddingButton={loaddingButton}></GetRiceDialog>

      </Layout>
    )
  }
}
